<template>
  <div>
    <table class="table table-bordered table-vertical-middle" v-loading="loading">
      <tr>
        <td
          :rowspan="9 + (isDebitTypeBank ? 1 : 0)"
          class="text-center font-weight-bold"
          width="4%"
        >
          委托担保合同
        </td>
        <td class="td-label" width="12%">贷款主体</td>
        <td colspan="3" width="36%">{{ relatedData.customer_name || '-' }}</td>
        <td class="td-label" width="12%">住所</td>
        <td colspan="3" width="36%">{{ relatedData.address || '-' }}</td>
      </tr>
      <tr>
        <td class="td-label">联系人</td>
        <td colspan="3">{{ relatedData.corp_name || '-' }}</td>
        <td class="td-label">联系电话</td>
        <td colspan="3">{{ relatedData.mobile_no || '-' }}</td>
      </tr>
      <tr>
        <td class="td-label">受托人</td>
        <td :class="inputTdCss" colspan="3">
          <span v-if="viewMode">{{ contract.accept_entrust_entity_name }}</span>
          <c-select
            v-else
            v-loading="agencyLoading"
            :options="agencies"
            :props="{ value: 'client_id', label: 'org_name' }"
            v-model="contract.gua_org_id"
            @change="handleAgencySelect"
            class="w-100"
          ></c-select>
        </td>
        <td class="td-label">受托人地址</td>
        <td colspan="3">{{ contract.accept_entrust_entity_address }}</td>
      </tr>
      <tr>
        <td class="td-label">贷款行</td>
        <td colspan="3">{{ relatedData.bank_name || '-' }}</td>
        <td class="td-label">贷款利率</td>
        <td :class="inputTdCss" colspan="3">
          <span v-if="viewMode">{{ contract.load_rate || '-' }}%</span>
          <div class="d-flex align-items-center" v-else>
            <input
              type="number"
              class="form-control"
              placeholder="请填写"
              v-model="contract.load_rate"
            />
            <span class="px-3 text-muted">%</span>
          </div>
        </td>
      </tr>
      <tr>
        <td class="td-label">合同类型</td>
        <td colspan="2" :class="inputTdCss">
          <span v-if="viewMode">{{ enumContractType[contract.contract_type || 1] || '-' }}</span>
          <el-radio-group v-else v-model="contract.contract_type">
            <el-radio
              v-for="(label, value) of enumContractType"
              :key="value"
              :label="value"
              class="mx-2"
            >
              {{ label }}
            </el-radio>
          </el-radio-group>
        </td>
        <td :class="inputTdCss">
          <span v-if="viewMode">{{ contract.credit_contract_no || '-' }}</span>
          <div class="d-flex align-items-center" v-else>
            <input
              class="form-control"
              placeholder="合同编号"
              v-model="contract.credit_contract_no"
            />
          </div>
        </td>
        <td class="td-label">授信/借款金额</td>
        <td :class="inputTdCss" colspan="3">
          <span v-if="viewMode">{{ contract.reply_funds || '-' }}万元</span>
          <div class="d-flex align-items-center" v-else>
            <input
              type="number"
              class="form-control"
              placeholder="请填写"
              v-model="contract.reply_funds"
              @input="calcBankBillFunds"
            />
            <div class="px-3 text-muted" style="min-width: 60px">万元</div>
          </div>
        </td>
      </tr>
      <tr>
        <td class="td-label">保证合同号</td>
        <td :class="inputTdCss" colspan="3">
          <span v-if="viewMode">{{ contract.ensure_contract_no || '-' }}</span>
          <div class="d-flex align-items-center" v-else>
            <input
              class="form-control"
              placeholder="请填写"
              v-model="contract.ensure_contract_no"
            />
          </div>
        </td>
        <td class="td-label">期限</td>
        <td :class="inputTdCss" colspan="3">
          <span v-if="viewMode">{{ contract.load_years || '-' }}年</span>
          <div class="d-flex align-items-center" v-else>
            <input
              type="number"
              class="form-control"
              placeholder="请填写"
              v-model="contract.load_years"
            />
            <span class="px-3 text-muted">年</span>
          </div>
        </td>
      </tr>
      <tr>
        <td class="td-label">担保债务类型</td>
        <td :class="inputTdCss" colspan="7">
          <span v-if="viewMode">{{ debitType[contract.debt_type || 1].label || '-' }}</span>
          <div class="px-3" v-else>
            <c-radio-group :options="debitType" v-model="contract.debt_type"></c-radio-group>
          </div>
        </td>
      </tr>
      <tr v-if="isDebitTypeBank">
        <td class="td-label">银行承兑汇票比例</td>
        <td :class="inputTdCss" colspan="3">
          <span v-if="viewMode">{{ contract.bank_accept_bill_rate || '-' }}%</span>
          <div class="d-flex align-items-center" v-else>
            <input
              type="number"
              class="form-control"
              placeholder="请填写"
              v-model="contract.bank_accept_bill_rate"
              @input="calcBankBillFunds"
            />
            <span class="px-3 text-muted">%</span>
          </div>
        </td>
        <td class="td-label">银行承兑汇票金额</td>
        <td colspan="3">
          <div class="d-flex justify-content-between">
            <span>{{ contract.bank_accept_bill_funds }}</span>
            <span class="text-muted">元</span>
          </div>
        </td>
      </tr>
      <tr>
        <td class="td-label">担保费率</td>
        <td :class="inputTdCss" colspan="3">
          <span v-if="viewMode">{{ contract.gua_rate || '-' }}%</span>
          <div class="d-flex align-items-center" v-else>
            <input
              v-input-number="{ min: 0, max: 100, fixed: 2 }"
              class="form-control"
              placeholder="请填写"
              v-model="contract.gua_rate"
            />
            <span class="px-3 text-muted">%</span>
          </div>
        </td>
        <td class="td-label">担保费(合计)</td>
        <td :class="inputTdCss" colspan="3">
          <span v-if="viewMode">{{ contract.gua_fee || '-' }}元</span>
          <div class="d-flex align-items-center" v-else>
            <input
              v-input-number="{ min: 0, fixed: 2 }"
              class="form-control"
              placeholder="请填写担保费"
              v-model="contract.gua_fee"
            />
            <div class="px-3 text-muted">元</div>
          </div>
        </td>
      </tr>
      <tr>
        <td class="td-label">借款种类</td>
        <td :class="inputTdCss" colspan="3">
          <span v-if="viewMode">{{ contract.loan_type || '-' }}</span>
          <input v-else class="form-control" placeholder="请填写" v-model="contract.loan_type" />
        </td>
        <td class="td-label">起始日期</td>
        <td :class="inputTdCss" width="14%">
          <span v-if="viewMode">{{ contract.load_date || '-' }}</span>
          <el-date-picker
            v-else
            v-model="contract.load_date"
            type="date"
            placeholder="起始日期"
            class="w-100 start-date-pick"
          ></el-date-picker>
        </td>
        <td class="td-label">结束日期</td>
        <td :class="inputTdCss">
          <span v-if="viewMode">{{ contract.load_end_date || '-' }}</span>
          <el-date-picker
            v-else
            v-model="contract.load_end_date"
            type="date"
            placeholder="结束日期"
            class="w-100 start-date-pick"
          ></el-date-picker>
        </td>
      </tr>
    </table>

    <div class="text-center py-4" v-if="!viewMode">
      <el-button type="primary" class="btn-long" :loading="submitLoading" @click="submit">
        {{ hasContract ? '修改' : '提交' }}委托合同
      </el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { enumContractType } from '@/credit/plugins/enumTown'
import { nzhToMoney } from '@vimi/utils-tool'

export default {
  components: {},
  props: {
    loading: Boolean,
    relatedData: {
      type: Object,
      default: () => ({}),
    },
    viewMode: {
      type: Boolean,
      default: false,
    },
    isRenewal: Boolean,
  },
  data() {
    return {
      enumContractType,
      agencies: [],
      agencyLoading: false,

      debitType: [
        { value: 1, label: '个人贷款' },
        { value: 2, label: '项目贷款' },
        { value: 3, label: '开立银行承兑汇票' },
        { value: 4, label: '其他债务' },
      ],

      submitLoading: false,
      contract: {
        gua_org_id: '',
        contract_type: '1',
        load_date: '',
        load_end_date: '',
      },
    }
  },
  computed: {
    ...mapGetters(['user', 'entrustContract']),
    relatedId() {
      return this.relatedData.customer_related_id
    },
    queryAddressCode() {
      return this.user.queryAddressCode || this.user.addressCode || '520600000000'
    },
    orgRegionLever() {
      return this.user.orgRegionLever
    },
    hasContract() {
      return !!this.entrustContract.entrust_contract_id
    },
    isDebitTypeBank() {
      return +this.contract.debt_type === 3
    },
    replyFunds() {
      return +(this.relatedData.res_funds || this.relatedData.reply_funds) || 0
    },
    inputTdCss() {
      return this.viewMode ? '' : 'input-td'
    },
  },
  watch: {
    entrustContract: {
      handler: function () {
        this.initContractByExist()
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    this.getAgency()
  },
  mounted() {},
  methods: {
    // 受托人（担保公司，区县和市一级）列表
    async getAgency() {
      if (!this.queryAddressCode || !this.orgRegionLever) return
      let params = {}
      if (+this.relatedData.gua_type === 2) {
        params = { 'client_id.eq': this.relatedData.service_id }
      } else {
        params = {
          'orWhere.client_id.eq': [this.relatedData.service_id, this.relatedData.recommend_service],
        }
      }
      this.agencyLoading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, 'credit_select_view', params, {
          N1address_code: 'asc',
        })
      )
      this.agencyLoading = false

      const data = (res && res.data) || []
      this.agencies = data

      if (!this.hasContract) {
        this.setContractAcceptAgency(this.agencies[0])
      }
    },

    handleAgencySelect(value) {
      const agency = this.agencies.find(item => item.client_id === value)
      this.setContractAcceptAgency(agency)
    },

    setContractAcceptAgency(agency) {
      if (!agency) return
      this.contract.gua_org_id = agency.client_id
      this.contract.accept_entrust_entity_name = agency.org_name
      this.contract.accept_entrust_entity_address = agency.address || ''
      this.contract.gua_org_code = agency.org_code
      this.contract.gua_org_name_short = agency.org_name_short
      this.contract.accept_entrust_entity_corp = agency.corp_name
      this.contract.accept_entrust_entity_phone = agency.phone_number
    },

    initContractByExist() {
      if (this.hasContract) {
        this.contract = { ...this.entrustContract }
        this.contract.debt_type = +this.contract.debt_type
        this.setByRelatedIfEmpty()
        if (!this.contract.reply_funds) {
          this.$set(this.contract, 'reply_funds', this.replyFunds)
        }
      } else {
        this.initContractByRelated()
      }
    },

    initContractByRelated() {
      this.contract = {
        gua_org_id: '',
        entrust_entity_name: this.relatedData.customer_name,
        entrust_entity_address: this.relatedData.address,
        bank_name: this.relatedData.bank_name,
        load_rate: this.relatedData.load_rate,
        reply_funds: this.replyFunds,
        load_years: this.relatedData.load_years,
        customer_related_id: this.relatedData.customer_related_id,
        gua_rate: this.relatedData.gua_rate,
        approval_fee: this.relatedData.approval_fee,
        load_date: this.relatedData.load_date || '',
        load_end_date: this.relatedData.load_end_date || '',
      }
    },

    setByRelatedIfEmpty() {
      ;['load_rate', 'reply_funds', 'load_years', 'gua_rate', 'approval_fee'].forEach(key => {
        if (!this.contract[key]) {
          this.$set(this.contract, key, this.relatedData[key])
        }
      })
    },

    submit() {
      if (!this.validator()) return
      if (this.isDebitTypeBank && !this.validatorBankBill()) return
      this.contract.reply_funds_capital = nzhToMoney(this.contract.reply_funds * 10000)
      this.contract.approval_fee_capital = nzhToMoney(this.contract.approval_fee)
      this.contract.sign_date = this.$utils.dateFormat(new Date(), 'yyyy-MM-dd')
      this.contract.gua_fee_capital = nzhToMoney(this.contract.gua_fee)
      this.contract.load_date = this.$utils.dateFormat(this.contract.load_date, 'yyyy-MM-dd')
      this.contract.load_end_date = this.$utils.dateFormat(
        this.contract.load_end_date,
        'yyyy-MM-dd'
      )
      this.contract.entrust_entity_phone = this.relatedData.mobile_no
      this.contract.entrust_entity_corp = this.relatedData.corp_name
      this.contract.entrust_entity_cert_no =
        this.relatedData.register_no || this.relatedData.lender_idcard
      if (this.hasContract) {
        this.putData()
      } else {
        this.postData()
      }
    },

    validator() {
      const enumValid = {
        gua_org_id: '请选择受托人',
        load_rate: '请填写贷款利率',
        credit_contract_no: '请填写授信合同/借款编号',
        reply_funds: '请填写授信/借款金额',
        ensure_contract_no: '请填写保证合同号',
        load_years: '请填写期限',
        gua_rate: '请填写担保费率',
        gua_fee: '请填写担保费（合计）',
        // approval_fee: '请填写评审费',
        loan_type: '请填写借款种类',
        load_date: '请选择起始日期',
        load_end_date: '请选择结束日期',
      }

      const keys = Object.keys(enumValid)
      for (const key of keys) {
        if (!this.contract[key]) {
          this.$message.error(enumValid[key])
          return false
        }
      }

      return true
    },

    validatorBankBill() {
      const enumValid = {
        bank_accept_bill_rate: '请输入银行承兑汇票比例',
      }

      const keys = Object.keys(enumValid)
      for (const key of keys) {
        if (!this.contract[key]) {
          this.$message.error(enumValid[key])
          return false
        }
      }

      return true
    },

    async putData() {
      this.submitLoading = true
      const { sign_no: signNO, doc_id: docId, ...data } = { ...this.contract }
      const [res] = await this.$utils.promise(
        this.$api.updateData(
          this.$serviceName,
          'entrust_contract',
          this.contract.entrust_contract_id,
          data
        )
      )
      this.submitLoading = false
      if (res) {
        this.$message.success('修改委托合同成功')
        this.$emit('success', 0)
      } else {
        this.$message.error('修改委托合同失败')
      }
    },

    async postData() {
      this.submitLoading = true
      const [res] = await this.$utils.promise(
        this.$api.addData(this.$serviceName, 'entrust_contract', {
          ...this.contract,
          // 是否是续贷
          is_extended_loan: this.isRenewal ? 1 : 0,
        })
      )
      this.submitLoading = false
      if (res) {
        this.$message.success('提交委托合同成功')
        this.$emit('success', 1)
      } else {
        this.$message.error('提交委托合同失败')
      }
    },

    // calcEndDate() {
    //   if (this.contract.load_years.length > 2) {
    //     this.contract.load_years = '99'
    //   }
    //   if (+this.contract.load_years <= 0) {
    //     this.contract.load_years = ''
    //   }

    //   if (this.contract.load_years && this.contract.load_date) {
    //     const date = new Date(this.contract.load_date)

    //     const year = date.getFullYear() + Number.parseInt(this.contract.load_years)
    //     const month = date.getMonth() + 1
    //     const day = Math.min(date.getDate(), new Date(year, month, 0).getDate())

    //     this.$set(this.contract, 'load_end_date', `${year}-${this.panStart(month)}-${this.panStart(day)}`)
    //   }
    // },

    panStart(str) {
      return `${str || ''}`.padStart(2, '0')
    },

    calcBankBillFunds() {
      let rate = Number.parseFloat(this.contract.bank_accept_bill_rate)
      const funds = Number.parseFloat(this.contract.reply_funds)

      if (funds > this.replyFunds) {
        this.contract.reply_funds = this.replyFunds
        this.$message.error(`不能大于审批金额${this.replyFunds}万元`)
      } else if (funds < 0) {
        this.contract.reply_funds = ''
        this.$message.error(`不能小于0`)
      }

      let value = ''
      if (!isNaN(rate) && !isNaN(funds)) {
        if (rate > 100) {
          this.contract.bank_accept_bill_rate = 100
          rate = 100
        }

        value = Math.round(rate * funds * 1e2)
      }
      this.contract.bank_accept_bill_funds = value
    },
  },
}
</script>
<style lang="scss" scoped>
.table-vertical-middle td {
  vertical-align: middle;
}
.td-label {
  background-color: #f8f9fa;
  text-align: center;
}
.input-td {
  background-color: #ffffee;
}
.start-date-pick /deep/ .el-input__inner {
  padding-right: 0.5rem;
}
</style>
